package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RestController
@Api(tags = "菜品接口")
@RequestMapping("/admin/dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 保存菜品和口味
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("保存菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        //删除reids的对应分类的缓存数据
        Long categoryId = dishDTO.getCategoryId();
        redisTemplate.delete("dish_"+categoryId);
        dishService.saveWithFlavor(dishDTO);
        return Result.success("保存成功");
    }


    /**
     * 分页查询（带条件）
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页接口")
    public Result page(DishPageQueryDTO dishPageQueryDTO){
        PageResult page = dishService.page(dishPageQueryDTO);
        return Result.success(page);
    }

    @ApiOperation("删除接口")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        cleanCache("dish_*");
        dishService.deleteByIds(ids);
        return Result.success();
    }

    /**
     * 修改菜品和对应的口味
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改接口")
    public Result update(@RequestBody DishDTO dishDTO){
        cleanCache("dish_*");
        dishService.updateById(dishDTO);
        return Result.success("修改成功");
    }

    /**
     * 回显数据
     * @param id
     * @return
     */
    @ApiOperation("根据id回显数据")
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Long id){
        DishVO dishVO = dishService.getById(id);
        return Result.success(dishVO);
    }


    /**
     * 根据分类id展示菜品（在添加套餐时展示）
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id展示菜品")
    public Result list(Long categoryId){
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    /**
     * 起售或停售自己实现
     * @param status
     * @param id
     * @return
     */
    @ApiOperation("起售或停售")
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id){
        cleanCache("dish_*");
        dishService.startOrStop(status,id);
        return Result.success();
    }

    /**
     * 清理redis缓存数据
     * @param key
     */
    public void cleanCache(String key){
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
